##### Vectorize lioness matrices of individual samples and combine into a single matrix ######
##### Read lioness networks: Female (GTEx)
rm(list=ls())
gender = "female"

library(data.table)
setwd(paste("/home/ubuntu/Thyroid_lioness_", gender, "/", sep = ""))
files_ls = list.files(path=".", pattern=".txt", all.files=TRUE,
                      full.names=TRUE)

indices = unlist(lapply(files_ls, function(x){unlist(strsplit(x, split = ".", fixed = T))[3]}))

# Read TF_gene names from PANDA networks
panda = read.table(paste("/home/ubuntu/thyroid_panda_", gender, ".txt", sep = ""), quote="\"", comment.char="")
panda = data.frame(panda)

indegree = aggregate(panda$V4, by=list(Category=panda$V2), FUN=sum)

genes = indegree[,1]

data = list()
i=0
for (file_name in files_ls){
  i = i+1
  new_data = fread(file_name)
  data[[i]] = colSums(new_data)
  cat(paste(i,"\n"))
}

lioness = do.call(cbind, data)

rownames(lioness) = genes
colnames(lioness) = indices

head(lioness)
dim(lioness)

setwd("/home/esaha/BONOBO/network/")
write.table(lioness, file=paste("lioness_Thyroid_", gender, ".txt", sep = ""), row.names=T, col.names=T)

######################################
library(data.table)
setwd("/home/ubuntu/BonoboPanda_GTEx_thyroid/single_panda/")
files_ls = list.files(path=".", pattern=".txt", all.files=TRUE,
                      full.names=TRUE)

indices = unlist(lapply(gsub("\\/*","",files_ls), function(x){unlist(strsplit(x, split = ".", fixed = T))[2]}))
data = list()
i=1
new_data = fread(files_ls[1])
new_data = aggregate(new_data$force, by=list(Category=new_data$gene), FUN=sum)
genes = new_data$Category

for (file_name in files_ls){
  new_data = fread(file_name)
  data[[i]] = aggregate(new_data$force, by=list(Category=new_data$gene), FUN=sum)$x
  cat(paste(i,"\n"))
  i = i+1
}

lioness = do.call(cbind, data)

rownames(lioness) = genes
colnames(lioness) = indices

head(lioness)
dim(lioness)

setwd("/home/esaha/BONOBO/network/")
write.table(lioness, file="BonoboPanda_GTEx_thyroid.txt", row.names=T, col.names=T)
